package com.leon.datalink.core.utils;

import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

public class ScriptUtil {

    private static final DecimalFormat decimalFormat = new DecimalFormat("#.#");

    /**
     * js脚本结果对象转为java对象
     * 注意：此方法已简化，移除了对Nashorn ScriptObjectMirror的依赖
     */
    public static Object toJavaObject(Object scriptObj) {
        // 简化实现：处理基本类型转换
        if (scriptObj instanceof Map) {
            Map<?, ?> sourceMap = (Map<?, ?>) scriptObj;
            Map<String, Object> map = Maps.newHashMap();
            for (Map.Entry<?, ?> entry : sourceMap.entrySet()) {
                map.put(String.valueOf(entry.getKey()), toJavaObject(entry.getValue()));
            }
            return map;
        } else if (scriptObj instanceof List) {
            List<?> sourceList = (List<?>) scriptObj;
            List<Object> list = Lists.newArrayList();
            for (Object item : sourceList) {
                list.add(toJavaObject(item));
            }
            return list;
        } else if (scriptObj instanceof Double) {
            // js脚本处理后的整型和浮点都会返回浮点并且被java表示为科学计数法
            // 移除科学技术法后判断如果是整数则转为整型
            String num = decimalFormat.format(scriptObj);
            if (num.contains(".")) {
                return scriptObj;
            } else {
                return NumberUtil.toBigInteger(num);
            }
        } else {
            return scriptObj;
        }
    }

}
